import { createSlice } from '@reduxjs/toolkit'
import { globalConfig } from '@/globalConfig'

// 先从localStorage里获取主题配置
const sessionTheme = JSON.parse(window.localStorage.getItem(globalConfig.SESSION_LOGIN_THEME))

// 如果localStorage里没有主题配置，则使用globalConfig里的初始化配置
const initTheme =  sessionTheme?sessionTheme: globalConfig.initTheme

const initialState = {
  dark: initTheme.dark,
  colorPrimary: initTheme.colorPrimary
}

export const themeSlice = createSlice({
  name: 'theme',
  initialState,
  reducers: {
    setDark: (state, action) => {
      state.dark = action.payload
      window.localStorage.setItem(globalConfig.SESSION_LOGIN_THEME, JSON.stringify(state))
    },
    setColorPrimary: (state, action) => {
      state.colorPrimary = action.payload
      window.localStorage.setItem(globalConfig.SESSION_LOGIN_THEME, JSON.stringify(state))
    }
  }
})

export const { setDark, setColorPrimary } = themeSlice.actions

export default themeSlice.reducer
